<template>
  <div class="tableBox">
    <el-dropdown style="margin: 7px">
      <nu-button>基本统计<i class="el-icon-arrow-down el-icon--right"></i></nu-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item v-for="(item, index) in statistics" :key="index">
          <el-checkbox v-model="checkAllData[index]" @change="(val) => checkboxChange(val, index, item)">{{ item
          }}</el-checkbox>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <nu-button>导出</nu-button>
    <!-- 横向表格 -->
    <div v-if="tableType == '横向' && isShowTable" class="box">
      <el-table :data="tableData" style="width: 100%" :height="tableHeight">
        <el-table-column v-for="(col, index) in columns" :label="col.label" :key="index" :prop="col.prop" align="center"
          :width="col.width">
          <div v-if="col.propsChildren">
            <el-table-column v-for="(child, childIndex) in col.propsChildren" :label="child.label" :key="childIndex"
              :prop="child.prop" align="center"></el-table-column>
          </div>
        </el-table-column>
      </el-table>
    </div>

    <!-- 纵向表格 -->
    <div v-if="tableType == '纵向' && isShowTable" class="box">
      <el-table :data="releaseTableData" style="width: 100%" :show-header="false" :cell-style="columnStyle"
        :span-method="objectSpanMethod" :height="tableHeight">
        <el-table-column v-for="(col, index) in releaseColumns" :label="col.label" :key="index" :prop="col.prop"
          :width="col.width" :fixed="col.fixed" align="center">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { mergeTableRow } from "@/utils/projects";
import nuButton from "@/components/base/button";
import {
  objectToQuery,
  getDateTime,
  getBeforeTime,
  groupBy,
  getMonthDays,
} from "@/utils/ruoyi";
export default {
  components: { nuButton },
  data() {
    return {
      tableType: "",
      isShowTable: false,
      columns: [],
      releaseColumns: [],
      checkAllData: [],
      tableData: [],
      pyunitIncrementsData: [],
      releaseTableData: [],
      statistics: ["最大值", "最小值", "求和", "均值"],
      statisticsData: [],
      resizeNum: 1,
      coeffic: {},
    };
  },
  props: {
    tableForm: {
      type: Object,
      default: () => {
        return {
          time: [],
          checkedMeasure: [],
          checkedDataItem: [],
        };
      },
    },
  },
  computed: {
    tableHeight: function () {
      let n =
        this.$parent.$refs.searchForm.$refs.formData.$el.offsetHeight +
        50 +
        160 +
        this.resizeNum;
      return "calc(100vh - " + n + "px)";
    },
  },
  watch: {
    tableForm: {
      handler(form) {
        this.tableType = form.align_type;
        this.isShowTable = false;
        this.checkAllData = []
        // console.log(this.checkAllData)
        this.getTableData();
      },
      immediate: true,
      deep: true,
    },
  },
  beforeMount() {
    window.addEventListener("resize", this.$_resizeHandler);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.$_resizeHandler);
  },
  mounted() { },
  methods: {
    $_resizeHandler() {
      if (!document.hidden) {
        this.resizeNum = Math.random();
      }
    },
    /**
     * 合并行
     * @param {*} param0
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // if (column.property === "nameType") {
      //   return row["nameType-span"];
      // }
      if (rowIndex === 0) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        }
      }
      if (column.property === "pointName") {
        return row["pointName-span"];
      }
    },
    /**
     * 返回行样式
     * @param {*} param0
     */
    columnStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        return "background:	#f8f8f9;";
      }
      if (columnIndex == 1) {
        return "background:	#f8f8f9;";
      }
    },
    /**
     * 基本统计-多选框change
     */
    checkboxChange(val, index, name) {
      let arr1 = {
        index: "",
        time: "",
      };
      let arr2 = {
        label: "",
        prop: "",
      };
      if (val) {
        if (this.tableType == "横向") {
          let a = JSON.parse(JSON.stringify(arr1));
          this.columns.forEach((c, j) => {
            if (j > 1) {
              this.statisticsData.forEach((item, i) => {
                if (c.label == item.pointName) {
                  c.propsChildren.forEach((e) => {
                    if (e.label == item.mesaName) {
                      switch (index) {
                        case 0:
                          a[e.prop] = item.max;
                          break;
                        case 1:
                          a[e.prop] = item.min;
                          break;
                        case 2:
                          a[e.prop] = item.sum;
                          break;
                        case 3:
                          a[e.prop] = item.average;
                          break;
                      }
                    }
                  });
                }
              });
            }
          });
          a.index = name;
          this.tableData.push(a);
        } else {
          let a = JSON.parse(JSON.stringify(arr2));
          a.prop = "num" + index;
          a.label = this.statistics[index];
          this.releaseColumns.push(a);
          this.releaseTableData[0][a.prop] = this.statistics[index];
          for (var i = 0; i < this.releaseTableData.length; i++) {
            this.statisticsData.forEach((item, s) => {
              if (this.releaseTableData[i + 1]['amount1'] == this.statisticsData[s].mesaName) {
                switch (index) {
                  case 0:
                    this.releaseTableData[i + 1][a.prop] =
                      this.statisticsData[s].max;
                    break;
                  case 1:
                    this.releaseTableData[i + 1][a.prop] =
                      this.statisticsData[s].min;
                    break;
                  case 2:
                    this.releaseTableData[i + 1][a.prop] =
                      this.statisticsData[s].sum;
                    break;
                  case 3:
                    this.releaseTableData[i + 1][a.prop] =
                      this.statisticsData[s].average;
                    break;
                }
              }
            });
          }
        }
      } else {
        if (this.tableType == "横向") {
          this.tableData.map((item, index) => {
            if (item.index == name) {
              this.tableData.splice(index, 1);
            }
          });
        } else {
          this.releaseColumns = this.releaseColumns.filter((res, i) => {
            return res.label !== this.statistics[index];
          });
        }
      }
    },

    /**
     * 设置横向表格头及横向表格数据格式化
     */
    setTableColumns() {
      let pointNames = {},
        mesaNames = {},
        data = [],
        startTimes = {};
      this.columns = [
        {
          label: "序号",
          prop: "index",
          propsChildren: null,
          width: 70,
        },
        {
          label: "时间",
          prop: "startTime",
          propsChildren: null,
          width: 150,
        },
      ];
      this.statisticsData = [];
      this.pyunitIncrementsData.forEach((item) => {
        if (item?.pointId && !item.hasOwnProperty('sum')) {
          if (
            Object.prototype.toString.call(pointNames[item.pointName]) ==
            "[object Array]"
          ) {
            pointNames[item.pointName].push(item);
          } else {
            pointNames[item.pointName] = [item];
          }
          if (
            Object.prototype.toString.call(mesaNames[item.mesaName]) ==
            "[object Array]"
          ) {
            mesaNames[item.mesaName].push(item);
          } else {
            mesaNames[item.mesaName] = [item];
          }
          let time = item.startTime || item.dataTime;
          if (
            Object.prototype.toString.call(startTimes[time]) == "[object Array]"
          ) {
            startTimes[time].push(item);
          } else {
            startTimes[time] = [item];
          }
        } else {
          this.statisticsData.push(item);
        }
      });
      let ki = 0,
        sT = 0,
        ji = 0;
      let arr = [];
      // console.log(pointNames,mesaNames,startTimes)
      // for (let k in startTimes) {
      //   let child = []
      //   startTimes[k].forEach((item, i) => {
      //     child.push({
      //       pointName: item.pointName,
      //       label: item.mesaName,
      //       prop: "power" + (i + 1),
      //       propsChildren: null,
      //       mesaType: item.mesaType
      //     });
      //   })
      //   arr.push(child)
      // }
      for (let k in pointNames) {
        let child = [];
        for (let j in mesaNames) {
          ji++;
          child.push({
            pointName: k,
            label: j,
            prop: "power" + ji,
            propsChildren: null,
            // mesaType: item.mesaType
          });
        }
        arr.push(child);
      }
      const sorted = groupBy(arr[0], function (item) {
        return [item.pointName];
      });
      sorted.forEach((item) => {
        // item.sort((a, b) => {
        //   return a.mesaType - b.mesaType
        // })
        this.columns.push({
          label: item[0].pointName,
          prop: "dynamo" + ki,
          propsChildren: item,
        });
      });
      for (let t in startTimes) {
        if (t != 'undefined') {
          sT++;
          Array.from({ length: this.coeffic.c }, (v, i) => {
            let k = i + 1;
            let date = new Date(t);
            date.setMinutes(this.coeffic.e * (k - 1));
            let d = getDateTime("min", date);
            let obj = {
              index: k + (sT - 1) * this.coeffic.c,
              startTime: d,
            };
            startTimes[t].forEach((item, j) => {
              let key = "";
              if (this.tableForm.data_grarity.indexOf("时") > -1) {
                key = "V" + (k - 1 < 10 ? "0" + (k - 1) : k - 1);
              } else if (this.tableForm.data_grarity.indexOf("天") > -1) {
                key = "V" + (k < 10 ? "0" + k : k);
              } else {
                key = "V" + k;
              }
              obj["power" + (j + 1)] = item[key];
            });
            data.push(Object.assign({}, obj));
          });
        }
      }
      // for(let m in mesaNames){
      //   let obj = {}
      //   let j = 0
      //     mesaNames[m].forEach((item, j) => {
      //       console.log(j)
      //       obj['power' + (j + 1)] = item[key]
      //       j++
      //     })
      //     data.push(Object.assign({}, obj))
      // }
      this.tableData = data;
    },
    /**
     * 设置纵向表格及纵向表格数据格式化
     */
    setReleaseColumns() {
      let pointNames = {},
        mesaNames = {},
        data = [],
        startTimes = {};
      this.releaseColumns = [
        {
          label: "名称",
          prop: "pointName",
          width: 130,
          fixed: true,
        },
      ];
      this.statisticsData = [];
      this.pyunitIncrementsData.forEach((item) => {
        if (item?.pointId && !item.hasOwnProperty('sum')) {
          if (
            Object.prototype.toString.call(pointNames[item.pointName]) ==
            "[object Array]"
          ) {
            pointNames[item.pointName].push(item);
          } else {
            pointNames[item.pointName] = [item];
          }
          if (
            Object.prototype.toString.call(mesaNames[item.mesaName]) ==
            "[object Array]"
          ) {
            mesaNames[item.mesaName].push(item);
          } else {
            mesaNames[item.mesaName] = [item];
          }
          let time = item.startTime || item.dataTime;
          if (
            Object.prototype.toString.call(startTimes[time]) == "[object Array]"
          ) {
            startTimes[time].push(item);
          } else {
            startTimes[time] = [item];
          }
        } else {
          this.statisticsData.push(item);
        }
      });
      for (let m in pointNames) {
        const sorted = groupBy(pointNames[m], function (item) {
          return [item.mesaName];
        });
        sorted.forEach((item, i) => {
          let obj = {};
          let mi = 2;
          obj["pointName"] = item[0].pointName;
          obj["amount1"] = item[0].mesaName;
          item.forEach((o) => {
            Array.from({ length: this.coeffic.c }, (v, i) => {
              let k = i + 1;
              let key = "";
              if (this.tableForm.data_grarity.indexOf("时") > -1) {
                key = "V" + (k - 1 < 10 ? "0" + (k - 1) : k - 1);
              } else if (this.tableForm.data_grarity.indexOf("天") > -1) {
                key = "V" + (k < 10 ? "0" + k : k);
              } else {
                key = "V" + k;
              }
              obj["amount" + mi] = o[key];
              mi++;
            });
          });
          data.push(Object.assign({}, obj));
        });
      }
      let c = {
        pointName: "时间",
        amount1: "时间",
      },
        ci = 2;
      for (let t in startTimes) {
        if (t != 'undefined') {
          Array.from({ length: this.coeffic.c }, (v, i) => {
            var date = new Date(t);
            let k = i + 1;
            date.setMinutes(this.coeffic.e * (k - 1));
            let d = getDateTime("min", date);
            let obj = {
              label: d,
              prop: "amount" + (ci - 1),
            };
            c["amount" + ci] = d;
            ci++;
            this.releaseColumns.push(obj);
          });
        }
      }
      this.releaseColumns.push({
        label: "amount" + this.releaseColumns.length,
        prop: "amount" + this.releaseColumns.length,
      });
      this.releaseColumns[1]["fixed"] = true;
      data.unshift(c);
      data = mergeTableRow(data, ["pointName"]);
      this.releaseTableData = data;
    },

    /**
     * 获取表格数据
     */
    getTableData() {
      if (JSON.stringify(this.tableForm) == "{}") {
        return false;
      }
      let postData = {
        // pointName: this.tableForm.checkedMeasure.join(),
        // measName: this.tableForm.checkedDataItem.join(),
        pointName: "",
        measName: "",
        startTime:
          typeof this.tableForm.time == "object"
            ? this.tableForm.time?.[0]
            : this.tableForm.time,
      };
      if (typeof this.tableForm.time == "object") {
        postData["endTime"] = this.tableForm.time?.[1];
      }
      const apis = {
        每15min增量值: window.api.getPyunitMinuteIncrements,
        每15min原值: window.api.getPyunitMinuteOriginals,
        每小时增量值: window.api.getPyunitDayIncrements,
        每天增量值: window.api.getPyunitMonthIncrements,
        每月增量值: "",
        每小时原值: window.api.getPyunitDayOriginals,
        每天原值: window.api.getPyunitMonthOriginals,
      };
      const coeffics = {
        每15min增量值: { c: 96, e: 15 },
        每15min原值: { c: 96, e: 15 },
        每小时增量值: { c: 24, e: 60 },
        每天增量值: { c: getMonthDays(), e: 24 * 60 },
        每月增量值: "",
        每小时原值: { c: 24, e: 60 },
        每天原值: { c: getMonthDays(), e: 24 * 60 },
      };
      let paramsStr = objectToQuery(postData);
      if (apis?.[this.tableForm.data_grarity]) {
        this.$httpGet(apis[this.tableForm.data_grarity] + paramsStr)
          .then((res) => {
            this.isShowTable = true;
            if (res.code == 200) {
              // let map = new Map();
              // for (let item of res.pyunitIncrements) {
              //   if (item.hasOwnProperty("pointId")) {
              //     map.set(item.pointId, item);
              //   } else if (item.hasOwnProperty("average")) {
              //     map.set(item.pointName + item.mesaName, item);
              //   }
              // }
              // this.pyunitIncrementsData = [...map.values()];
              this.pyunitIncrementsData = res.pyunitIncrements
              this.coeffic = coeffics[this.tableForm.data_grarity];
              if (this.tableForm.align_type == "纵向") {
                this.setReleaseColumns();
              } else {
                this.setTableColumns();
              }
            } else {
              this.pyunitIncrementsData = [];
              this.tableData = [];
              this.releaseTableData = [];
            }
          })
          .catch((err) => {
            this.pyunitIncrementsData = [];
            this.tableData = [];
            this.releaseTableData = [];
          });
      } else {
        this.pyunitIncrementsData = [];
        this.tableData = [];
        this.releaseTableData;
      }
    },
  },
};
</script>
<style scoped>
.tableBox {
  /* border: 1px solid rgba(228, 228, 228, 1); */
  background-color: rgba(248, 249, 252, 1);
}

.box {
  border-top: 1px solid rgba(228, 228, 228, 1);
}
</style>